package ru.kest.torrentwatchlist.parsing.nnm;

import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import ru.kest.torrentwatchlist.parsing.ParsingException;
import ru.kest.torrentwatchlist.parsing.TorrentCollector;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by kkharitonov on 27.11.2014.
 */
public class NNMTorrentCollector implements TorrentCollector{

    private static Logger logger = Logger.getLogger("NNMTorrentCollector");

    @Autowired
    private ApplicationContext appContext;

    private String torrentsListUrl;

    public NNMTorrentCollector(String torrentsListUrl) {
        this.torrentsListUrl = torrentsListUrl;
    }

    @Override
    public int parse() {
        int resultCount = 0;
        logger.info("Parsing of NNM started. Url: " + torrentsListUrl);

        NNMScraper scraper = appContext.getBean(NNMScraper.class);

        try {
            for(String url : getTorrentsList()) {
                if (scraper.scrape(url)) {
                    resultCount++;
                }
            }
        } catch (ParsingException e) {
            logger.error(e.getMessage(), e);
        }

        return resultCount;
    }

    private List<String> getTorrentsList() throws ParsingException {
        List<String> result = new ArrayList<String>();
        try {
            Document doc = Jsoup.connect(torrentsListUrl).get();
            doc.getElementsByClass("forumline").first();
            Elements links = doc.getElementsByClass("forumline").first().select("a[href][class=topictitle]");
            logger.info("Found " + links.size() + " items");
            for (Element link : links) {
                result.add(link.attr("abs:href"));
            }
        } catch (IOException e) {
            throw new ParsingException("Can't get url list", e);
        }
        return result;
    }
}
